<template>
  <h1 style="margin: 0px 0px 40px 80px;" v-if="userType === 1">订单列表</h1>
  <h1 style="margin: 0px 0px 40px 80px;" v-if="userType === 0">我的订单</h1>

  <span style="margin-left: 200px;" v-if="userType == 1">用户名</span>
  <input type="text" placeholder="请输入用户名" v-model="loginName" v-if="userType == 1">
  <span style="margin-left: 20px;">创建时间</span>
  <input type="date" v-model="createDate" />
  <span style="margin-left: 20px;">是否付款</span>
  <select v-model="status">
    <option value="0" selected>全部</option>
    <option value="1">未付款</option>
    <option value="2">已付款</option>
  </select>
  <span style="margin-left: 20px;">订单号</span>
  <input type="text" v-model="serialNumber" />

  <a href="#" class="addNews" @click.prevent="goToPage(1)">搜索</a>

  <div v-if="pageInfo.list.length === 0">暂无订单</div>

  <div class="order-container" v-for="order in pageInfo.list">
    <!-- 订单头部信息 -->
    <div class="order-header">
      <div class="order-info">
        <div class="user-info">
          用户名: {{ order.loginName }}<br />
          支付方式：{{ order.payMent }}<br />
          收件人：{{ order.name }}
        </div>
        <div class="order-number">
          创建时间：{{ order.createTime }}<br />
          地址: {{ formatAddress(order.userAddress) }}<br />
          收件人联系电话：{{ order.phone }}
        </div>
        <div class="address">
          订单号: {{ order.serialNumber }}<br />
          <div class="order-status">
            <span v-if="order.status === 1">
              <span v-if="orderCountdowns[order.id] > 0" class="countdown-text">
                支付倒计时：{{ formatCountdown(orderCountdowns[order.id]) }}
              </span>
              <span v-else class="countdown-expired">已过期</span>
            </span>
            <span v-if="order.status === 2">已付款</span>
            <span v-if="order.status === 3">订单超时关闭</span>
            <span v-if="order.status === 4">订单关闭</span>
          </div>
        </div>
        <div class="total-price">
          总价: {{ order.cost }}<br />
          <button class="pay-btn" @click="goPay(order.serialNumber,order.payMent)"
            v-if="userType == 0 && order.status === 1 && orderCountdowns[order.id] > 0">前往付款</button>
          <button class="cancel-btn" @click="closeOrder(order.id,order.payMent)" v-if="order.status === 1 && orderCountdowns[order.id] > 0">关闭订单</button>
          <button class="cancel-btn" @click="refundOrder(order.serialNumber)"
            v-if="userType == 0 && order.status === 2 && order.payMent=='支付宝' ">退款</button>
        </div>
      </div>
    </div>

    <!-- 商品列表表格 -->
    <div class="products-table-container">
      <table class="products-table">
        <thead>
          <tr>
            <th>商品名称</th>
            <th>商品图片</th>
            <th>数量</th>
            <th>价格</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(product, index) in order.products" :key="index">
            <td>{{ product.name }}</td>
            <td>
              <img :src="urlImg + product.fileName" :alt="product.name" class="product-image">
            </td>
            <td>{{ product.quantity }}</td>
            <td>{{ product.quantity * product.price }}</td>
          </tr>
        </tbody>
      </table>
    </div>


  </div>
  <!-- 分页控件 -->
  <div class="pagination" style="margin-top: 10px; text-align: right;" v-if="pageInfo.pages > 1">
    <button @click="goToPage(1)" :disabled="pageInfo.pageNum === 1">首页</button>
    <button v-for="page in pageInfo.navigatepageNums" :key="page" @click="goToPage(page)" :style="{
      backgroundColor: pageInfo.pageNum === page ? '#ccc' : 'transparent',
      margin: '0 3px',
      padding: '2px 8px'
    }">
      {{ page }}
    </button>
    <button @click="goToPage(pageInfo.pageNum + 1)" :disabled="pageInfo.pageNum === pageInfo.pages">下一页</button>
    <button @click="goToPage(pageInfo.pages)" :disabled="pageInfo.pageNum === pageInfo.pages">尾页</button>
  </div>

      <!-- 弹窗 -->
        <div class="modal-overlay" v-if="showModal">
            <div class="modal">
                <div class="modal-header">
                    <h2 class="modal-title">微信支付</h2>
                    <button  class="close-button" @click="closeModal">&times;</button><!-- 关闭弹窗 -->
                </div>
                
                <div class="form-group">
                  <img :src="qrCodeDataUrl" alt="微信支付二维码" />
                  <p>请使用微信扫描二维码完成支付</p>
                </div>

   
                <div class="modal-actions">
                    <button class="cancel-btn" @click="toReturn()">完成</button>
                </div>
            </div>
        </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import axios from 'axios'// 导入axios库
import { useRouter } from 'vue-router' // 导入路由
import QRCode from 'qrcode'
const router = useRouter();

const urlImg = 'http://192.168.12.159:83/';

const loginName = ref('');
const createDate = ref('');
const status = ref('');
const serialNumber = ref('');
const userType = ref(2);
const currentTime = ref(new Date());
const countdownTimer = ref(null); // 添加定时器引用

const qrCodeDataUrl = ref('')
const showModal = ref(false);// 显示/隐藏弹窗
const outTradeNo = ref('');
const formatCountdown = (seconds) => {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = seconds % 60;
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
};


// 为所有订单创建倒计时映射
const orderCountdowns = computed(() => {
  const countdowns = {};
  pageInfo.value.list.forEach(order => {
    if (order.status === 1) {
      const paymentLimit = 15 * 60 * 1000;
      const createDateTime = new Date(order.createTime).getTime();
      const expireTime = createDateTime + paymentLimit;
      const now = currentTime.value.getTime();

      const countdown = Math.max(0, Math.floor((expireTime - now) / 1000));
      countdowns[order.id] = countdown;
    } 
  });
  return countdowns;
});


// 启动倒计时定时器
const startCountdownTimer = () => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value);
  }

  countdownTimer.value = setInterval(() => {
    currentTime.value = new Date();


  }, 1000);
};



const storedType = sessionStorage.getItem("type");//0,1
if (storedType != null) {
  userType.value = storedType;
}
if (userType.value == 0) {
  loginName.value = sessionStorage.getItem("loginName");
}

const pageInfo = ref({
  list: [],        //orders列表
  pageNum: 1,      // 当前页码
  pageSize: 3,    // 每页大小
  total: 1,        // 总记录数
  pages: 1,        // 总页数
  navigatepageNums: [1],// 导航页码
})

// 格式化地址显示
function formatAddress(userAddress) {
  if (!userAddress || !userAddress.length) return '';
  const parts = userAddress.split(' ');
  if (parts.length >= 3) {
    // 按照规范添加完整后缀
    return parts[0] + "省" + parts[1] + "市" + parts[2] + "区" + (parts[3] || '');
  }
  return userAddress;
}

//微信支付
const payWX = async (serialNumber) => {

  showModal.value = true;//打开弹窗 

outTradeNo.value = serialNumber;

  try {
    // 调用后端接口生成支付二维码
    const response = await axios.get('/api/wxzf',{
      params: {
            serialNumber: serialNumber
        },
    })
    if (response.data.code == 5200) {
      // 使用QRCode库生成二维码
      qrCodeDataUrl.value = await QRCode.toDataURL(response.data.pay_url)
    }
    console.log(response.data);
    
  } catch (error) {
    console.error('生成支付二维码失败:', error)
  }

}



// 关闭弹窗
const closeModal = () => {
    showModal.value = false;
};



// 获取所有订单
const fetchOrders = async () => {
  try {
    const response = await axios.post('/api/allOrder', {
      pageNum: pageInfo.value.pageNum,
      pageSize: pageInfo.value.pageSize,
      loginName: loginName.value,
      createTime: createDate.value,
      status: status.value,
      serialNumber: serialNumber.value
    })
    pageInfo.value = response.data//pageInfo
    console.log("date", response.data);

    if (pageInfo.value.pages == 0) {
      pageInfo.value.pages = 1;
    }
  } catch (error) {
    console.error('获取数据失败:', error)
  }
}



// 分页方法
const goToPage = (pageNum) => {
  if (pageNum >= 1 && pageNum <= pageInfo.value.pages) {
    console.log("页码合法");

    pageInfo.value.pageNum = pageNum;
    fetchOrders();
  }
};

const toReturn = ()=>{
  console.log(outTradeNo.value);
  
  router.push({
    name: 'return',
    query: {
      serialNumber:outTradeNo.value
    }
  })
}
const goPay = async (serialNumber,payMent) => {
  console.log(serialNumber);
  
  if (payMent == "支付宝") {
    try {
      const response = await axios.get('api/payOrder', {
        params: {
          serialNumber: serialNumber
        },

      })
      // 使用 Vue 的 ref 或响应式数据来处理返回的内容，而不是直接操作 DOM
      console.log(response.data);
      if (response.data.code == 5500) {
        alert(response.data.reason)

      }

      const paymentFormHtml = response.data;
      // 创建一个临时的 div 元素来解析 HTML 字符串
      const tempDiv = document.createElement('div');
      tempDiv.innerHTML = paymentFormHtml;

      // 获取表单元素
      const form = tempDiv.querySelector('form');
      if (form) {
        // 将表单添加到页面中
        document.body.appendChild(form);
        // 提交表单
        form.submit();
      } else {
        console.error('未找到支付表单');
      }
    } catch (error) {
      console.error(error)
    }
  }else{
    //微信支付
    payWX(serialNumber);
  }
}

//关闭订单
const closeOrder = async (orderId) => {
  if (!confirm("确定关闭订单吗？")) {
    return;
  }
  try {
    const response = await axios.get('/api/closeOrder?id=' + orderId)
    if (response.data.code == 5500) {
      alert("关闭订单失败");
    } else {
      alert("关闭订单成功");
      fetchOrders();
    }
  } catch (error) {
    console.error('关闭订单失败:', error)
  }
}




//退款
const refundOrder = async (serialNumber) => {
  if (!confirm("确定退款吗？")) {
    return;
  }
  try {
    const response = await axios.get('/api/refundOrder?serialNumber=' + serialNumber)
    if (response.data.code == 5500) {
      alert("退款失败");
    } else {
      alert("退款成功");
      fetchOrders();
    }
  } catch (error) { }
}

onMounted(() => {
  fetchOrders();
  startCountdownTimer(); // 启动倒计时
})

onUnmounted(() => {
  // 组件卸载时清除定时器
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value);
  }
})
</script>

<style scoped>

.modal-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.save-btn {
    background: #3498db;
    color: white;
}

.save-btn:hover {
    background: #2980b9;
}

.cancel-btn {
    background: #95a5a6;
    color: white;
}

.cancel-btn:hover {
    background: #7f8c8d;
}


.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.modal {
    background: white;
    border-radius: 10px;
    width: 90%;
    max-width: 400px;
    padding: 25px;
    box-shadow: 0 5px 20px rgba(0, 0, 0, 0.2);
}

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;
}

.modal-title {
    font-size: 1.3rem;
    color: #2c3e50;
}

.close-button {
    background: none;
    border: none;
    font-size: 1.5rem;
    color: #7f8c8d;
    cursor: pointer;
}

.form-group {
    /* margin-bottom: 20px; */
    
     display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  margin-top: 20px;
}


.pay-btn {
  background-color: #10b981;
  color: white;
}

.cancel-btn {
  background-color: #ef4444;
  color: white;
}

.form-group {
  margin-bottom: 20px;
}

.addNews {
  margin: 10px;
  padding: 0 10px;
  border: 1px solid #555555;
}

.order-container {
  max-width: 1000px;
  margin: 20px auto;
  padding: 20px;
  font-family: Arial, sans-serif;
  border: 1px solid #e0e0e0;
  border-radius: 5px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.order-header {
  padding-bottom: 15px;
  border-bottom: 1px solid #e0e0e0;
}

.order-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  font-size: 14px;
}

.total-price {
  flex: 1;
}

.user-info {
  flex: 2;

}

.order-number,
.address {
  flex: 4;
  margin: 0;
}

.total-price {
  color: #e53e3e;
  font-weight: bold;
}

.products-table-container {
  overflow-x: auto;
}

.products-table {
  width: 100%;
  border-collapse: collapse;
  text-align: left;
}

.products-table th,
.products-table td {
  padding: 12px 15px;
  border-bottom: 1px solid #e0e0e0;
}

.products-table th {
  background-color: #f5f5f5;
  font-weight: bold;
}

.product-image {
  width: 50px;
  height: 50px;
  object-fit: contain;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .order-info {
    flex-direction: column;
    gap: 10px;
  }

  .products-table th,
  .products-table td {
    padding: 8px 10px;
  }
}

.countdown-text {
  color: #ff0000;
  /* 红色 */
  font-weight: bold;
  font-size: 14px;
  /* 可以添加一些动画效果，比如闪烁 */
  animation: blink 1s infinite;
}

.countdown-expired {
  color: #999;
  font-weight: bold;
}

/* 闪烁动画 */
@keyframes blink {
  0% {
    opacity: 1;
  }

  50% {
    opacity: 0.5;
  }

  100% {
    opacity: 1;
  }
}

.countdown-timer {
  display: flex;
  align-items: center;
}

.time-block {
  display: inline-block;
  background: #e4393c;
  color: white;
  padding: 4px 6px;
  border-radius: 3px;
  font-size: 14px;
  font-weight: bold;
  min-width: 24px;
  text-align: center;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.time-separator {
  margin: 0 4px;
  color: #e4393c;
  font-weight: bold;
  font-size: 16px;
}

.countdown-hint {
  font-size: 12px;
  color: #999;
  margin-left: 8px;
}

.countdown-expired {
  color: #999;
  font-weight: bold;
}

.countdown-container {
  display: inline-flex;
  align-items: center;
  margin-top: 5px;
}

.countdown-container {
  flex-direction: column;
  align-items: flex-start;
}

.countdown-label {
  font-size: 14px;
  color: #666;
  margin-right: 8px;
}
</style>
